import React, { Component,createRef } from 'react'

export default class Todo extends Component {
  constructor(){
    super()
    this.state = {
      isEdit:false  //任务是否处于编辑状态
    }
    this.editInput = createRef()
    this.handleEdit = this.handleEdit.bind(this)
  }
  handleEdit(bool=true){ //控制任务编辑状态
    this.setState({
      isEdit:bool
    },()=>{
      this.editInput.current.focus()  //使得编辑框自动获取焦点
    })
    let {handleUpdate,objectId} = this.props
    if(!bool){
      handleUpdate(objectId,this.editInput.current.value) 
      //触发父组件的事件函数，并传递指定数据
    }
    
  }
  render() {
    let {taskname,isCheck,objectId} = this.props
    let {handleCheck,handleDel} = this.props
    let complete = isCheck?'completed':''
    let edit = this.state.isEdit?'editing':''
    return (
      <li 
        className={`${complete} ${edit}`}
        onDoubleClick={this.handleEdit}
      >
        <div className="view">
          <input 
            type="checkbox" 
            className="toggle" 
            checked={isCheck}
            onChange={()=>{
              handleCheck(objectId)
            }}
          />
          <label>{taskname}</label>
          <button className="destroy" onClick={()=>{
            handleDel(objectId)
          }}></button>
        </div>
        <input 
          type="text" 
          className="edit" 
          ref={this.editInput}
          defaultValue={taskname}
          onBlur={()=>{this.handleEdit(false)}}
        />
      </li>
    )
  }
}
